package com.sanxiau.dormitory.yang.service.impl;


import com.sanxiau.dormitory.yang.entity.*;
import com.sanxiau.dormitory.yang.face.FaceDetect;
import com.sanxiau.dormitory.yang.face.FaceSearch;
import com.sanxiau.dormitory.yang.mapper.AttendanceMapper;
import com.sanxiau.dormitory.yang.mapper.LoginMapper;
import com.sanxiau.dormitory.yang.service.AttendanceService;
import com.sanxiau.dormitory.yang.util.GetAfterDay;
import com.sanxiau.dormitory.yang.vo.ResultInfo;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*学生个人考勤实现类代码*/
@Service
public class AttendanceServiceImpl implements AttendanceService {

    @Autowired
    LoginMapper loginMapper;
    @Autowired
    AttendanceMapper attendanceMapper;
    /*识别人脸信息*/
    @Override
    public ResultInfo faceshow(String base64) {
        ResultInfo resultInfo = new ResultInfo();
        try {
            JSONObject jsonObject = new JSONObject(FaceDetect.faceDetect(base64));
            String error_code = jsonObject.getString("error_code");
            if (error_code.equals("0")) {
                JSONObject jsonObject1 = (JSONObject) jsonObject.get("result");
                JSONArray jsonArray = jsonObject1.getJSONArray("face_list");
                JSONObject jsonObject2 = (JSONObject) jsonArray.get(0);
                JSONObject jsonObject3 = (JSONObject) jsonObject2.get("location");
                double[] d = {jsonObject3.getDouble("left"), jsonObject3.getDouble("top"), jsonObject3.getDouble("width"), jsonObject3.getDouble("height")};
                if (null == d) {
                    System.out.println("未检测出人脸");
                    resultInfo.setMessage("未检测出人脸");
                    resultInfo.setDd(new double[]{0, 0, 0, 0});
                } else {
                    resultInfo.setDd(d);
                }
            }
            } catch(JSONException e){
                e.printStackTrace();
            }

        return resultInfo;
    }
    /*对人脸信息进行验证，完成考勤*/
    @Override
    @Transactional
    public ResultInfo addAttendance(String base64, Model model, HttpSession session)  {
        ResultInfo resultInfo = new ResultInfo();
        int userid = -1;
        String jpg1 = "";

        try {
            jpg1 = FaceDetect.faceDetect(base64);
        }catch (Exception e){
            resultInfo.setMessage("考勤失败，请重新操作");
            e.printStackTrace();
            return resultInfo;
        }

        JSONObject json0 = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Student student1 = attendanceMapper.queryStudentByStu_id(session.getAttribute("userName")+"");
        Attendance attendance = attendanceMapper.queryAttendanceFalse(format.format(date), GetAfterDay.getSpecifiedDayAfter(format.format(date)),session.getAttribute("userName")+"");
        if (null != attendance){
            System.out.println("今天已完成考勤，请不要重复操作");
            resultInfo.setMessage("今天已完成考勤，请不要重复操作");
        }else {
            Dorout dorouts = attendanceMapper.queryDoroutsByOut_date(format.format(date),student1.getHou_id(),student1.getDor_id());
            if (null == dorouts) {
                resultInfo.setMessage("现在无法考勤");
            } else {
                long start = dorouts.getCheck_start().getTime();
                long end = dorouts.getCheck_end().getTime();
                long now = date.getTime();
                if (now > end) {
                    resultInfo.setMessage("超过考勤时间");
                    System.out.println("超过考勤时间");
                } else if (now < start) {
                    resultInfo.setMessage("未到考勤时间");
                    System.out.println("未到考勤时间");
                } else {
                    System.out.println("可以考勤");
                    try {
                        json0 = new JSONObject(jpg1);
                        int error_code1 = json0.getInt("error_code");
                        if (error_code1 > 0) {
                            resultInfo.setMessage("采集失败,请重试");
                            System.out.println("Detect采集失败,请重试");
                        } else {
                            String jpg = FaceSearch.faceSearch(base64);
                            JSONObject json1 = new JSONObject(jpg);
                            int error_code = json1.getInt("error_code");
                            if (error_code > 0) {
                                resultInfo.setMessage("验证失败,请重试");
                                System.out.println("验证失败,请重试");
                            } else {
                                JSONObject json2 = (JSONObject) json1.get("result");
                                JSONArray user_list = json2.getJSONArray("user_list");
                                JSONObject user = (JSONObject) user_list.get(0);
                                String user_id = user.getString("user_id");
                                userid = Integer.parseInt(user_id);
                                resultInfo.setId(userid);
                                System.out.println("验证成功");
                            }
                        }
                        LoginIn loginIn = loginMapper.queryUserByID(userid);
                        if (null != loginIn) {
                            Student student = attendanceMapper.queryStudentByStu_id(loginIn.getUser_name());
                            if (student.getStu_id().equals(session.getAttribute("userName"))) {
                                attendance = new Attendance();
                                attendance.setStu_id(student.getStu_id());
                                attendance.setStu_name(student.getStu_name());
                                attendance.setStu_sex(student.getStu_sex());
                                attendance.setHou_id(student.getHou_id());
                                attendance.setDor_id(student.getDor_id());
                                attendance.setStu_study(student.getStu_study());
                                attendance.setStu_class(student.getStu_class());
                                attendance.setStu_cname(student.getStu_cname());
                                attendance.setCheck_time(new Date());
                                int num = attendanceMapper.addAttendanceRecord(attendance);
                                if (num > 0) {
                                    int out_nub = dorouts.getOut_nub();
                                    if (out_nub > 0) {
                                        out_nub = out_nub - 1;
                                        if (out_nub == 0) {
                                            dorouts.setOut_sf("true");
                                        }
                                        dorouts.setOut_nub(out_nub);
                                        int num1 = attendanceMapper.updateDorout(dorouts);
                                        if (num1 > 0) {
                                            System.out.println("考勤成功");
                                            resultInfo.setMessage("考勤成功");
                                        } else {
                                            try {
                                                throw new Exception("修改考勤记录出现问题，抛出异常，进行事务回滚");
                                            } catch (Exception e) {
                                                System.out.println("考勤失败,请重新操作");
                                                resultInfo.setMessage("考勤失败，请重新操作");
                                                e.printStackTrace();
                                                return resultInfo;
                                            }
                                        }
                                    } else {
                                        try {
                                            throw new Exception("修改考勤记录出现问题，抛出异常，进行事务回滚");
                                        } catch (Exception e) {
                                            System.out.println("考勤失败,请重新操作");
                                            resultInfo.setMessage("考勤失败，请重新操作");
                                            e.printStackTrace();
                                            return resultInfo;
                                        }
                                    }
                                } else {
                                    try {
                                        throw new Exception("添加个人考勤记录出现问题，抛出异常，进行事务回滚");
                                    } catch (Exception e) {
                                        System.out.println("考勤失败,请重新操作");
                                        resultInfo.setMessage("考勤失败，请重新操作");
                                        e.printStackTrace();
                                        return resultInfo;
                                    }

                                }
                            } else {
                                System.out.println("请本人完成考勤");
                                resultInfo.setMessage("请本人完成考勤");
                            }
                        }else {
                            System.out.println("请先添加你的照片信息");
                            resultInfo.setMessage("请先添加你的照片信息");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return resultInfo;
    }
    /*查询所有学个人生的考勤信息*/
    @Override
    public List<Attendance> allAttendance() {
        List<Attendance> attendances = attendanceMapper.queryAllAttendance();
        if (null==attendances){
            System.out.println("attendances查询失败");
        }else {
            System.out.println("attendances查询成功");
        }
        return attendances;
    }

    @Override
    public LoginIn queryUserByUser_name(HttpSession session) {
        LoginIn loginIn = attendanceMapper.queryUserByUser_name(session.getAttribute("userName")+"");
        if (null==loginIn){
            System.out.println("loginIn查询失败");
        }else {
            System.out.println("loginIn查询成功");
        }
        return loginIn;
    }

    @Override
    public List<Dorm> queryAllHous() {
        List<Dorm> dorms = attendanceMapper.queryAllHous();
        /*List<String> hous = new ArrayList<>();
        for (int i = 0; i < dorms.size(); i++) {
            hous.add(dorms.get(i).getHou_id());
        }*/
        return dorms;
    }

    @Override
    public List<String> queryAllDors(String hou) {
        List<Dorm> dorms = attendanceMapper.queryAllDors(hou);
        List<String> dors = new ArrayList<>();
        for (int i = 0; i < dorms.size(); i++) {
            dors.add(dorms.get(i).getDor_id());
        }
        return dors;
    }

    @Override
    public ResultInfo setCause(String hou_id, String dor_id, String text,HttpSession session) {
        ResultInfo resultInfo = new ResultInfo();
        if (null == hou_id || "".equals(hou_id) || null == dor_id || "".equals(dor_id) || null == text || "".equals(text)){
            System.out.println("内容不能为空");
            resultInfo.setMessage("内容不能为空，提交失败，请重试");
        }else {
            Student student = attendanceMapper.queryStudentByStu_id(session.getAttribute("userName")+"");
            System.out.println("student:"+student);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            if (null == student || !student.getHou_id().equals(hou_id) || !student.getDor_id().equals(dor_id)){
                System.out.println("student缺勤原因添加失败");
                resultInfo.setMessage("信息错误，提交失败，请重试");
            }else {
                Dorout dorout = new Dorout();
                try {
                    dorout.setOut_date(format.parse(format.format(date)));
                    dorout.setHou_id(hou_id);
                    dorout.setDor_id(dor_id);
                    dorout.setOut_why(student.getStu_name() + ":" + text);
                    int num = attendanceMapper.updateOut_why(dorout);
                    if (num < 0) {
                        System.out.println("updateOut_why缺勤原因添加失败");
                        resultInfo.setMessage("提交失败，请重试");
                    } else {
                        System.out.println("缺勤原因添加成功");
                        resultInfo.setMessage("缺勤原因添加成功");
                    }
                } catch (ParseException e) {
                    System.out.println("缺勤原因添加失败");
                    resultInfo.setMessage("提交失败，请重试");
                    e.printStackTrace();
                    return resultInfo;
                }
            }
        }
        return resultInfo;
    }
}
